package com.shiwaixiangcun.customer.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.mobstat.SendStrategyEnum;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.shiwaixiangcun.customer.GlobalApi;
import com.shiwaixiangcun.customer.R;
import com.shiwaixiangcun.customer.adapter.CompanyDetailListAdapter;
import com.shiwaixiangcun.customer.base.BaseActivity;
import com.shiwaixiangcun.customer.entity.DecorateDetailBean;
import com.shiwaixiangcun.customer.event.EventUtil;
import com.shiwaixiangcun.customer.event.SimpleEvent;
import com.shiwaixiangcun.customer.glide.ImageDisplayUtil;
import com.shiwaixiangcun.customer.interfaces.RequestPermissionType;
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut;
import com.shiwaixiangcun.customer.utils.Utils;
import com.shiwaixiangcun.customer.widget.ChangeLightImageView;
import com.shiwaixiangcun.customer.widget.MyListView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static butterknife.internal.Utils.arrayOf;

/**
 * 找装修详情页面
 * @author Administrator
 */

public class CompanyDetailActivity extends BaseActivity implements View.OnClickListener, ListView.OnItemClickListener {

    private ChangeLightImageView back_left;
    private MyListView lv_detail_cunpany;
    private List<String> list_company = new ArrayList<>();

    private LinearLayout mGallery;
    private LinearLayout ll_onclick_open;
    private TextView tv_detail;
    private ScrollView sv_company;
    private String recoratingId;
    private ImageView iv_logo_top;
    private TextView tv_title_detail;
    private TextView tv_instruct;
    private List<DecorateDetailBean.DataBean.DecoratePlanDtosBean> decoratePlanDtos;
    private TextView tv_call_phone;
    private String phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company_detail);
        //        百度统计
        StatService.setLogSenderDelayed(10);
        StatService.setSendLogStrategy(this, SendStrategyEnum.APP_START, 1, false);
        StatService.setSessionTimeOut(30);

        Intent intent = getIntent();
        recoratingId = intent.getStringExtra("recoratingId");

        layoutView();
        initData();

        EventUtil.getInstance().register(this);
    }

    private void layoutView() {

        back_left = findViewById(R.id.back_left);
        lv_detail_cunpany = findViewById(R.id.lv_detail_cunpany);
        ll_onclick_open = findViewById(R.id.ll_onclick_open);
        tv_detail = findViewById(R.id.tv_detail);
        sv_company = findViewById(R.id.sv_company);
        iv_logo_top = findViewById(R.id.iv_logo_top);
        tv_title_detail = findViewById(R.id.tv_title_detail);
        tv_instruct = findViewById(R.id.tv_instruct);
        tv_call_phone = findViewById(R.id.tv_call_phone);
        sv_company.smoothScrollTo(0, 20);
        sv_company.setFocusable(true);
        lv_detail_cunpany.setFocusable(false);
        back_left.setOnClickListener(this);
        lv_detail_cunpany.setOnItemClickListener(this);
        ll_onclick_open.setOnClickListener(this);
        tv_call_phone.setOnClickListener(this);
    }

    private void initData() {
        OkGo.<String>get(GlobalApi.INSTANCE.getCompanyDetail())
                .params("id", recoratingId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DecorateDetailBean recoratingDetailBean = new Gson().fromJson(response.body(), DecorateDetailBean.class);
                        if (recoratingDetailBean.getResponseCode() == 1001) {

                            EventUtil.getInstance().post(new SimpleEvent(SimpleEvent.UPDATE_DETAIL_DECORATE, 1, recoratingDetailBean));
                        }
                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setInfo(SimpleEvent simpleEvent) {
        if (simpleEvent == null || simpleEvent.mEventType != SimpleEvent.UPDATE_DETAIL_DECORATE) {
            return;
        }
        switch (simpleEvent.mEventValue) {
            case 1:
                DecorateDetailBean result = (DecorateDetailBean) simpleEvent.getData();
                setInfo(result);
                break;
            default:
                break;

        }

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.back_left:
                finish();
                break;
            case R.id.ll_onclick_open:
                ll_onclick_open.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_call_phone:
                showRingDialog();
                break;
            default:
                break;

        }
    }


    private void getlt(final List<DecorateDetailBean.DataBean.CertificatesBean> certificates) {
        mGallery = findViewById(R.id.id_gallery);



        for (int i = 0; i < certificates.size(); i++) {

            View view = LayoutInflater.from(this).inflate(R.layout.item_image, mGallery, false);
            ImageView iv_certificates = view.findViewById(R.id.iv_certificates);
            if (Utils.isNotEmpty(certificates.get(i).getThumbImageURL())) {
                ImageDisplayUtil.showImageView(this, certificates.get(i).getThumbImageURL(), iv_certificates);
            }
            final int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String url_bit_image = certificates.get(finalI).getAccessUrl();
                    Intent intent = new Intent(CompanyDetailActivity.this, BigImageActivity.class);
                    intent.putExtra("bigimagelist", (Serializable) certificates);
                    intent.putExtra("serid", finalI);
                    startActivity(intent);
                }
            });
            mGallery.addView(view);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(CompanyDetailActivity.this, CompanyDetailToDetailActivity.class);
        intent.putExtra("serlist", (Serializable) decoratePlanDtos);
        intent.putExtra("idDetail", i + "");
        intent.putExtra("phone", phone);
        startActivity(intent);
    }


    /**
     * 设置信息
     *
     * @param result
     */
    public void setInfo(DecorateDetailBean result) {
        phone = result.getData().getPhone();
        if (Utils.isNotEmpty(result.getData().getLogo())) {
            ImageDisplayUtil.showImageView(this, result.getData().getLogo(), iv_logo_top);
        }
        tv_title_detail.setText(result.getData().getName());
        tv_detail.setText(result.getData().getIntroduce());
        tv_instruct.setText(result.getData().getSummary());
        List<DecorateDetailBean.DataBean.CertificatesBean> certificates = result.getData().getCertificates();
        getlt(certificates);
        decoratePlanDtos = result.getData().getDecoratePlanDtos();
        CompanyDetailListAdapter companyDetilListAdapter = new CompanyDetailListAdapter(decoratePlanDtos, this);
        lv_detail_cunpany.setAdapter(companyDetilListAdapter);

    }

    /**
     * 显示拨打电话对话框
     */
    private void showRingDialog() {
        final DialogLoginOut dialogLoginOut = new DialogLoginOut(CompanyDetailActivity.this, R.layout.item_dialog_call_phone);
        dialogLoginOut.setTitle("是否要拨打此电话？");
        dialogLoginOut.setMessage(phone);
        dialogLoginOut.setYesOnclickListener("是", new DialogLoginOut.OnPositiveOnclickListener() {
            @Override
            public void onYesClick() {
                dialogLoginOut.dismiss();
                requestPermission(phone);
            }
        });

        dialogLoginOut.setNoOnclickListener("否", new DialogLoginOut.OnPassiveOnclickListener() {
            @Override
            public void onNoClick() {

                dialogLoginOut.dismiss();
            }
        });
        dialogLoginOut.show();
    }

    private void requestPermission(String number) {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE),
                        RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE);
                return;
            } else {
                callPhone(number);
            }
        } else {
            callPhone(number);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    callPhone(phone);
                } else {
                    // Permission Denied
                    showToastShort("未获取拨打电话权限");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    /**
     * 拨号方法
     */
    @SuppressLint("MissingPermission")
    private void callPhone(String number) {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
    }

    @Override
    protected void onDestroy() {
        EventUtil.getInstance().unregister(this);
        super.onDestroy();
    }
}
